package com.caucho.hessian.serializer;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import com.caucho.hessian.io.AbstractDeserializer;
import com.caucho.hessian.io.AbstractHessianInput;

public class ThrowableDeserializer extends AbstractDeserializer {

	@Override
	public Class getType() {
		return Throwable.class;
	}
	@Override
	public Object readMap(AbstractHessianInput in) throws IOException {
		int ref = in.addRef(null);
		byte[] initValue = null;
		while (!in.isEnd()) {
			String key = in.readString();
			if (key.equals("value"))
				initValue = in.readBytes();
			else
				in.readString();
		}
		in.readMapEnd();
		ByteArrayInputStream bis = new ByteArrayInputStream(initValue);
		ObjectInputStream ois = new ObjectInputStream(bis);
		try {
			Object value = ois.readObject();
			in.setRef(ref, value);
			return value;
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} finally {
			ois.close();
			bis.close();
		}
	}
	@Override
	public Object readObject(AbstractHessianInput in, Object[] fieldNames)
			throws IOException {
		int ref = in.addRef(null);
		byte[] initValue = null;
		for (Object o : fieldNames) {
			if (o instanceof String) {
				final String key = (String) o;
				if (key.equals("value"))
					initValue = in.readBytes();
				else
					in.readObject();
			}
		}
		ByteArrayInputStream bis = new ByteArrayInputStream(initValue);
		ObjectInputStream ois = new ObjectInputStream(bis);
		try {
			Object value = ois.readObject();
			in.setRef(ref, value);
			return value;
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} finally {
			ois.close();
			bis.close();
		}
	}
}